Skip to main content

Convert string to number

To convert string to number, we have to use Number.parseInt() method.

For example,

let str = "15";
Number.parseInt(str, 10); // 15
Note

In Number.parseInt(), Number is a global object which contains a method called parseInt(). Number.parseInt() method expects two parameters,

Number.parseInt(string, radix);

The first parameter is string which is to be converted to a number. The second is the radix, in most cases radix will be 10.

Note

The radix 10 is known as the decimal system (use the digits from 0 to 9). Another radix example is 2, which represents binary (a numerical system used by computers).

It is always better to pass radix as 10 as parameter. Even though radix is an optional parameter, it will not be always default to 10. In some cases there will be chance for problem, so it is safe to pass the radix.

Use cases for converting to a number

The most common is when a user enters a number into a text box or when the number is read from the DOM (which is explained later on).

These values will always be strings, as you will see in the following challenge (even if the user writes a number). It is therefore your responsibility to convert it to a number.

If you fail to convert a string to a number, the intended addition behaves similarly to concatenation.

For example,

let a = 12;
let b = "15"; // we forgot to convert it to a number
a + b; // 1215 (concatenation instead of sum)

Like this situations to avoid computation erros, it is better to use Number.parseInt() method.

For example,

Number.parseInt("2022 Year", 10); // 2022
Number.parseInt("10 Kilometers", 10); // 10

When the string starts with a number and ends with a number, at thus situation use the following Number.parseInt() method.

Note
Number.parseInt() === parseInt();

They both work exactly the same way. It is always better to follow modern approach Number.parseInt().